import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../../common/api/user_api.dart';
import '../../common/const/app_color_const.dart';
import '../../common/const/app_style_const.dart';
import '../../common/enum/btn_enum.dart';
import '../../common/type/user_type.dart';
import '../../common/util/common_util.dart';
import '../../common/util/store_util.dart';
import '../../router_table.dart';
import '../../widget/icon_outlined_btn.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => LoginPageState();
}

class LoginPageState extends State<LoginPage> {
  TextEditingController employeeNumCtrl = TextEditingController();
  TextEditingController passwordCtrl = TextEditingController();
  bool savePwd = false;

  @override
  void initState() {
    super.initState();
    //employeeNumCtrl.text = '000000';
    //passwordCtrl.text = 'admin';

    StoreUtil.getAccount().then((value) {
      if (null != value && null != value.employeeNum) {
        employeeNumCtrl.text = value.employeeNum!;
      }
      if (null != value && null != value.pwd) {
        passwordCtrl.text = value.pwd!;
      }

      if (null != value && null != value.employeeNum && null != value.pwd) {
        setState(() {
          savePwd = true;
        });
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    employeeNumCtrl.dispose();
    passwordCtrl.dispose();
  }

  login() {
    if (employeeNumCtrl.text.trim().isEmpty) {
      CommonUtil.showToast("请输入帐号！");
      return;
    }

    if (passwordCtrl.text.trim().isEmpty) {
      CommonUtil.showToast("请输入密码！");
      return;
    }

    Map<String, String> params = {
      "employeeNum": employeeNumCtrl.text.trim(),
      "pwd": passwordCtrl.text.trim()
    };

    UserApi.login(params).then((res) {
      if (null != res.data && res.data["isSuccess"]) {
        var data = res.data["data"];
        StoreUtil.setUserId(data["id"]);
        StoreUtil.setToken(data["token"]);
        StoreUtil.setUserInfo(UserInfoType.fromJson(data));
        CommonUtil.showToast("登录成功！");
        if (savePwd) {
          StoreUtil.setAccount(jsonEncode(params));
        }
        Navigator.of(context)
            .pushNamedAndRemoveUntil(RouterTable.homePath, (route) => false);
      } else {
        CommonUtil.showToast(res.data["msg"]);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
      fit: StackFit.expand,
      children: <Widget>[
        Positioned(
          right: 0,
          top: 0,
          child: Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height / 2,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  fit: BoxFit.cover,
                  alignment: Alignment.topCenter,
                  image: AssetImage('assets/images/login/login_header.png'),
                ),
              )),
        ),
        Positioned(
            right: 0,
            left: 0,
            top: MediaQuery.of(context).size.height / 2 - 300,
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: const [
                  Text(
                    "直播间工作台",
                    style: TextStyle(
                        color: whiteColor,
                        fontSize: 24,
                        fontWeight: FontWeight.bold),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 30.0),
                    child: Text(
                      "直播间内部员工使用的工作平台",
                      style:
                          TextStyle(color: lightGrayAccentColor5, fontSize: 16),
                    ),
                  )
                ])),
        Positioned(
            right: 30,
            left: 30,
            top: MediaQuery.of(context).size.height / 2 - 135,
            child: Container(
              width: MediaQuery.of(context).size.width,
              padding: const EdgeInsets.only(bottom: 20.0),
              decoration: BoxDecoration(
                color: whiteColor,
                boxShadow: [
                  BoxShadow(
                    blurRadius: 8,
                    spreadRadius: 2,
                    color: shadowColor1.withOpacity(0.25), //阴影颜色
                  ),
                ],
                borderRadius: BorderRadius.circular(12),
              ),
              child: Column(
                children: [
                  const Padding(
                    padding: EdgeInsets.only(top: 25.0, bottom: 25.0),
                    child: Text(
                      '登录',
                      style: TextStyle(fontSize: 22),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(
                        left: 20.0, right: 20.0, bottom: 15.0),
                    child: TextField(
                      controller: employeeNumCtrl,
                      minLines: 1,
                      maxLines: 1,
                      style: inputStyle,
                      inputFormatters: [LengthLimitingTextInputFormatter(64)],
                      decoration: const InputDecoration(
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.all(
                              Radius.circular(4),
                            ),
                            borderSide: BorderSide(
                              color: borderColor1,
                              width: 0.5,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(4),
                              ),
                              borderSide: borderStyle),
                          isDense: true,
                          labelText: "帐号：",
                          labelStyle: inputLabelStyle,
                          floatingLabelBehavior: FloatingLabelBehavior.never,
                          hintText: "请输入帐号！",
                          hintStyle: inputHintStyle,
                          alignLabelWithHint: true,
                          prefixText: '帐号：'),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(
                        left: 20.0, right: 20.0, bottom: 5.0),
                    child: TextField(
                      controller: passwordCtrl,
                      minLines: 1,
                      maxLines: 1,
                      keyboardType: TextInputType.visiblePassword,
                      obscureText: true,
                      style: inputStyle,
                      inputFormatters: [LengthLimitingTextInputFormatter(64)],
                      decoration: const InputDecoration(
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.all(
                              Radius.circular(4),
                            ),
                            borderSide: borderStyle,
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(4),
                              ),
                              borderSide: BorderSide(
                                color: borderColor1,
                                width: 0.5,
                              )),
                          isDense: true,
                          labelText: "密码：",
                          labelStyle: inputLabelStyle,
                          floatingLabelBehavior: FloatingLabelBehavior.never,
                          hintText: "请输入密码！",
                          hintStyle: inputHintStyle,
                          alignLabelWithHint: true,
                          prefixText: '密码：'),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 5.0, bottom: 5.0),
                    child: Row(
                      children: [
                        Checkbox(
                            value: savePwd,
                            onChanged: (value) {
                              setState(() {
                                savePwd = value!;
                              });
                            }),
                        const Text('保存帐号并自动登录')
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 20.0, right: 20.0),
                    child: IconOutlinedBtn(
                        text: '登录',
                        btnType: BtnType.primary,
                        onPressed: () {
                          login();
                        }),
                  )
                ],
              ),
            )),
        Positioned(
            left: 0,
            top:  MediaQuery.of(context).size.height-30,
            child: Container(
              width: MediaQuery.of(context).size.width,
              alignment: Alignment.center,
              child: Text(
                CommonUtil.getEnvConfig()["loginBottomTxt"],
                style: const TextStyle(color: grayColor, fontSize: 12),
              ),
            )),
        /*Positioned(
            left: MediaQuery.of(context).size.width / 2 - 45,
            top: MediaQuery.of(context).size.height / 2 - 170,
            child: Container(
              width: 90.0,
              height: 90.0,
              padding: const EdgeInsets.all(16.0),
              decoration: const BoxDecoration(
                  color: loginLogoBg,
                  borderRadius: BorderRadius.all(Radius.circular(60))),
              child: Image.asset(
                'assets/images/app_icon_1x.png',
              ),
            )),*/
      ],
    ));
  }
}
